package logic

import (
	"cart-master/cartrpc/cartrpc"
	"cart-master/cartrpc/internal/svc"
	"cart-master/model"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CartAddLogic) CartAdd(in *cartrpc.CartAddRequest) (*cartrpc.CartAddResponse, error) {
	// todo: add your logic here and delete this line

	var shop model.Shop
	err := model.DB.Debug().Where("id=?", in.ShopId).First(&shop).Error
	if err != nil {
		return nil, fmt.Errorf("该商品不存在")
	}
	if int64(shop.Num) < in.Quantity {

		return nil, fmt.Errorf("库存不足")
	}
	cart := model.Cart{
		ShopId:   int(in.ShopId),
		Quantity: int(in.Quantity),
		Amount:   float64(in.Amount),
	}
	model.DB.Debug().Create(&cart)
	return &cartrpc.CartAddResponse{
		CardId: int64(cart.ID),
	}, nil
}
